<?php
namespace app\daili\controller;
// use think\Db;
class Index extends Common{
    function index(){
        // // $this->redirect('member/member/index');
        // return view();
        
        // 判断用户是否登录
            // 未登录，跳转到登录页面
            // 已登录，获取代理的下级用户数量、代理获得的累加收益
            // 提交页面显示
        
        $uid=$this->user['id'];
            
        // 获取代理获得的累加收益
        $prices = model('finance')->where(['type'=>2,'uid'=>$uid])->sum('money');
        // $lowser = model('member')
        
        // 会员数量
        $num = $this->digui($this->user,$quantity=0);
        // var_dump($num);
        // $members=model('member')->where(['module_id'=>0])->count();

        // // 微手会员
        // $weishou=model('member')->where(['module_id'=>1])->count();
        // // 设备
        // $devs=model('device')->count();
        // // 账号
        // $softs=model('software')->count();
        // // 好友（微信客户）
        // $socials=model('social')->group('number')->count();
        // // 素材
        // $sources=model('source')->count();
        $options=[
            'countOption'=>[
                'xAxis'=>['下级数量','总分成'],
                'data'=>[$num,$prices],
            ],
            'activityOption'=>$this->activityOption(),
        ];
        $this->assign('options',json_encode($options));

        $finance=model('finance')->statis();
        $this->assign('finance',json_encode($finance));
        return view();
    }

    /**
     * 统计代理下级数量
     * @return int 返回数量
     */
    private function digui($data,$num){
        // 
        $list = model('member')->where('pid = '.$data['id'])->select();
        foreach ($list as $k => $val) {
            if (!empty($val)) {
                $num++;
                $num = $this->digui($val,$num);
            }
        }
        return $num;
    }

    /**
     * 今日活跃度统计（通过用户任务发布统计）
     * @return array
     */
    private function activityOption(){
        $time=strtotime(date('y-m-d'));
        $where=[
            's_time'=>['s_time','between',[$time,$time+86400]]
        ];
        $tasked=model('tasked')->readAll($where,0,['field'=>'member_id']);
        $tasking=model('tasking')->readAll($where,0,['field'=>'member_id']);
        $count=[];
        $ids=[];
        foreach ($tasked as $v) {
            if(isset($count[$v['member_id']])){
                $count[$v['member_id']]++;
            }else{
                $count[$v['member_id']]=1;
            }
            if(!in_array($v['member_id'], $ids)){
                array_push($ids,$v['member_id']);
            }
        }
        foreach ($tasking as $v) {
            if(isset($count[$v['member_id']])){
                $count[$v['member_id']]++;
            }else{
                $count[$v['member_id']]=1;
            }
            if(!in_array($v['member_id'], $ids)){
                array_push($ids,$v['member_id']);
            }
        }
        $rs=[];
        if(count($ids)){
            $map=[
                'id'=>['id','in',$ids]
            ];
            $members=model('member')->readAll($map,0,['field'=>'id,name']);
            $xAxis=[];
            $data=[];
            foreach($members as $v) {
                array_push($xAxis,$v['name']);
                array_push($data,[
                    'value'=>$count[$v['id']],
                    'name'=>$v['name'].'（'.$count[$v['id']].'）',
                ]);
            }
            $rs=[
                'xAxis'=>$xAxis,
                'data'=>$data,
            ];
        }else{
            $rs=[
                'xAxis'=>['今日活跃度'],
                'data'=>[['value'=>0,'name'=>'今日活跃度']],
            ];
        }
        return $rs;
    }

    // 获取代理的下级信息
    public function lowQuan(){
        // 获取不为代理的直属下级信息
        $user = $this->user;
        // $list = model('member')->readAll($map,0,['field'=>'id,name,remark,money,raw_money,level,ratio,label,id<0 as cid,id<0 as c_money']);

        // $s_time=input('s_time/s','');
        // $e_time=input('e_time/s','');
        // $params=[
        //     's_time'=>$s_time,
        //     'e_time'=>$e_time,
        //     'keyword'=>$keyword,
        //     'vip_level'=>input('vip_level/s','-1'),
        // ];
        $options=[
            'field'=>'id,name,tel,status,s_time,head_img,pid,vip_expire,vip_ratio,money,alipay,realname,vip_level,vip_id,is_agent',
        ];
        $module=model('artmodule')->read(['name'=>'single'],'id');
        $map=['module_id'=>$module['id']];
        $map=['is_agent'=>['is_agent','neq',1]];
        $map=['pid'=>$user['id']];
        // if(!empty($keyword)){
        //     $map['tel|name']=['tel|name','like',"%{$keyword}%"];
        // }
        // if($params['vip_level']>=0){
        //     $map['vip_level']=$params['vip_level'];
        // }
        // if(!empty($s_time)){
        //     if(empty($e)){
        //         $e_time=time();
        //     }
        //     $map['s_time']=['s_time','between',[$s_time,$e_time]];
        //     $params['range']=[$s_time*1000,$e_time*1000];
        // }elseif(!empty($e)){
        //     if(empty($s_time)){
        //         $s_time=0;
        //     }
        //     $map['s_time']=['s_time','between',[$s_time,$e_time]];
        //     $params['range']=[$s_time*1000,$e_time*1000];
        // }
        $list=model('member')->readAll($map,true,$options);
        $this->assign('list',$list);
        // print_r($list);die;

        $vip=model('vip')->readAll(['status'=>1],0,['field'=>'id,name,level'])->toArray();
        array_unshift($vip, ['level'=>-1,'name'=>'全部'], ['id'=>0,'level'=>0,'name'=>'非VIP']);
        $this->assign('vip',json_encode($vip));
        // $this->assign('params',json_encode($params));
        //p($list->toArray());
        return view();
    }


    public function lowList(){
        // 获取不为代理的直属下级信息
        $user = $this->user;

        $pid=input('pid/s','');
        $options=[
            'field'=>'id,name,tel,status,s_time,head_img,pid,vip_expire,vip_ratio,money,alipay,realname,vip_level,vip_id,is_agent',
        ];
        $module=model('artmodule')->read(['name'=>'single'],'id');
        $map=['module_id'=>$module['id']];
        $map=['is_agent'=>['is_agent','neq',1]];
        $map=['pid'=>$pid];
        $list=model('member')->readAll($map,true,$options);
        $this->assign('list',$list);
        // print_r($list);die;

        $vip=model('vip')->readAll(['status'=>1],0,['field'=>'id,name,level'])->toArray();
        array_unshift($vip, ['level'=>-1,'name'=>'全部'], ['id'=>0,'level'=>0,'name'=>'非VIP']);
        $this->assign('vip',json_encode($vip));
        return view();
    }
    
    // 获取代理的分成信息
    public function divideInto($type=-1,$now_time=null){
        $s_time=input('s_time/s','');
        $e_time=input('e_time/s','');
        $params=[
            's_time'=>$s_time,
            'e_time'=>$e_time,
            'type'=>$type,
            'cate'=>input('cate/d',1),
            'keyword'=>input('keyword/s',''),
        ];
        // var_dump($params['cate']);
        $map=[];
        $map['uid']=$this->user['id'];
        $map['from_id']=['from_id','neq',$this->user['id']];
        // from_id
        if($type>=0){
            $map['type']=$type;
        }
        if(!empty($params['keyword'])){
            if($params['cate']==1){
                $user=model('member')->readAll([
                    'name|tel'=>['name|tel','like',"%{$params['keyword']}%"]
                ],'id');
                $ids=[];
                foreach ($user as $v) {
                    $ids[]=$v['id'];
                }
            }elseif($params['cate']==2){
                $from=model('member')->readAll([
                    'name|tel'=>['name|tel','like',"%{$params['keyword']}%"]
                ],'id');
                $ids=[];
                foreach ($from as $v) {
                    $ids[]=$v['id'];
                }
                $map['from_id']=['from_id','in',$ids];
            }elseif($params['cate']==3){
                $order=model('order')->readAll([
                    'number'=>['number','like',"%{$params['keyword']}%"]
                ],'id');
                $ids=[];
                foreach ($order as $v) {
                    $ids[]=$v['id'];
                }
                $map['order_id']=['order_id','in',$ids];
            }
        }
        if(!empty($s_time)){
            if(empty($e)){
                $e_time=time();
            }
            $map['s_time']=['s_time','between',[$s_time,$e_time]];
            $params['range']=[$s_time*1000,$e_time*1000];
        }elseif(!empty($e)){
            if(empty($s_time)){
                $s_time=0;
            }
            $map['s_time']=['s_time','between',[$s_time,$e_time]];
            $params['range']=[$s_time*1000,$e_time*1000];
        }
        if(!is_null($now_time)){
            $map['now_time']=$now_time;
        }
        $options=[
            'order'=>'s_time desc',
            'with'=>['user','from','order']
        ];
        $list=model('finance')->readAll($map,true,$options)->appends($params);
        $this->assign('list',$list);
        // print_r($list->toArray());die;
        $this->assign('params',json_encode($params));
        return view();
    }

    // 查询用户信息
    public function userInfo(){
        $uid = $this->user['id'];
        $data = model('member')->read(['id'=>$uid]);
        // var_dump($data);
        $this->assign('data',$data);
        $userinfo = array(
                    'id'        =>$data['id'],
                    'tel'        =>$data['tel'],
                    'name'      =>$data['name'],
                    'alipay'    =>$data['alipay'],
                    'realname'  =>$data['realName'],
                    'remark'    =>$data['remark'],
                    // 'status'    =>$data['status'],
                    // 'is_agent'  =>$data['is_agent'],
            );
        $this->assign('userinfo',json_encode($userinfo));
        return view();
    }

    // 修改用户信息
    public function edit(){
        $uid = $this->user['id'];
        $data=[
            'id'=>input('id'),
            'tel'=>input('tel'),
            'name'=>input('name'),
            'alipay'=>input('alipay'),
            'realName'=>input('realname'),
            // 'remark'=>input('remark'),
            // 'status'=>input('status'),
            // 'tel'=>input('tel'),
        ];
        $validate=$this->validate($data,[
            'tel|手机号码'=>'require|mobile',
            'name|昵称'=>'require'
            // 'status|手机号码'=>'require'
        ]);
        // var_dump(input('post.'));die;
        // var_dump(true!==$validate);die;
        if(true!==$validate){
            $this->error($validate);
        }
        if ($uid != $data['id']) {
            $this->error('修改失败');
        }
        unset($data['tel']);
        // $data = model('member')->read($data);
        // var_dump($data);
        $edit=model('member')->edit($data);
        $this->success('修改成功');die;
    }

    // 修改登录密码
    public function editlogin(){

        $data=[
            'tel'=>input('tel'),
            'pwd'=>input('pwd'),
            'code'=>input('code'),
            'pwd1'=>input('pwd1'),
            'pwd2'=>input('pwd2'),
            // 'remark'=>input('remark'),
            // 'status'=>input('status'),
            // 'tel'=>input('tel'),
        ];
        $validate=$this->validate($data,[
            'tel|手机号码'=>'require|mobile',
            'code|短信验证码'=>'require',
            'pwd1|新密码'=>'require|min:6',
            'pwd2|确认密码'=>'require',
            // 'status|手机号码'=>'require'
        ]);
        if(true!==$validate){
            $this->error($validate);
        }

        $user = $this->user;

        if ($data['tel'] != $user['tel']) {
            $this->error('请输入绑定的手机号码');
        }

        if ($user['login_pwd'] != encrypt_pwd($data['pwd']) && $user['login_pwd'] != '') {
            $this->error('密码不正确');
        }

        if ($data['pwd1'] != $data['pwd2']) {
            $this->error('新密码与确认密码不一致，重新输入');
        }

        if ($data['pwd'] == $data['pwd1']) {
            $this->error('新密码与旧密码一致，重新输入');
        }
        // $map = array()
        // $data = model('member')->read($data);
        // var_dump($data);
        $edit=model('member')->where('tel = '.$data['tel'].' and code = '.$data['code'])->update(['login_pwd'=>encrypt_pwd($data['pwd1'])]);
        $rs=model('member')->read(['tel'=>$data['tel']]);
        
        // var_dump($user['login_pwd']);
        // var_dump(encrypt_pwd($data['pwd']));
        // print_r($edit);die;
        session(config('keys.daili_user'),$rs->toArray());
        // $rs=model('member')->read(['tel'=>$tel]);
        $this->success('修改成功');die;
    }

    /**
     * 发送验证码
     * @param  string $tel 手机号码
     * @param  string $deviceId 设备ID
     * @return [type]      [description]
     */
    function sendCode($tel=null,$deviceId=null){
        $data=[
            'tel'=>input('tel'),
        ];
        $validate=$this->validate($data,[
            'tel|手机号码'=>'require|mobile'
        ]);
        // var_dump(input('post.'));die;
        // var_dump(true!==$validate);die;
        if(true!==$validate){
            return json($validate,1);
        }

        $user = $this->user;

        if ($tel != $user['tel']) {
            return json('请输入绑定的手机号码',1);
        }
        // 验证手机号是否存在 如果不存在则进行新增
        $add=$this->_register($tel,0,true,$deviceId);
        // var_dump($add);die;
        if(!$add['success']){
            return json($add['msg'],1);
        }
        die;
        $add=$add['data'];
        if(!$add['status']){
            return json('该账号已被限制登录，请联系管理员或者使用别的账号',1);
        }
        $code=rand(10000,99999);
        $content=lang('send code',[$code]);
        $send=sms($tel,$content);
        if($send['code']!=0){
            return json($send['msg'],1);
        }
        $e=isset($add['code'])&&$code==$add['code'];
        // var_dump(isset($add['code']));
        // var_dump($code);
        // var_dump($add['code']);
        // var_dump($code==$add['code']);
        // var_dump($e);die;
        if(!$e){
            $e=model('member')->edit(['id'=>$add['id'],'code'=>$code]);
        }
        if($e){
            $data['id']=$add['id'];
            $data['time']=time();
            $token=Jwt::encode($data);
            return json('验证码发送成功',0,['token'=>$token['data']]);
            die;
        }
        return json('验证码发送失败',1);
    }

    function _register($tel,$pid=0,$checkTel=true,$deviceId=null){
        // var_dump($tel);die;
        if($checkTel){
            $has=model('member')->read(['tel'=>$tel,'is_agent'=>1],'id,code,status,deviceId1,deviceId2');
            if(!empty($has)){
                if(!is_null($deviceId)){
                    if(empty($has['deviceId1'])){
                        model('member')->edit(['deviceId1'=>$deviceId],['id'=>$has['id']]);
                        return success('',0,$has); 
                    }elseif(empty($has['deviceId2'])&&$has['deviceId1']!=$deviceId){
                        model('member')->edit(['deviceId2'=>$deviceId],['id'=>$has['id']]);
                        return success('',0,$has); 
                    }elseif($has['deviceId1']!=$deviceId&&$has['deviceId2']!=$deviceId){
                        return error('每个账号仅允许最多绑定两台设备',1); 
                    }
                }
                return success('',0,$has);
            }
            else{
                return error('手机号未注册，或者您还不是代理',1);
            }
        }
        $data=[
            'tel'=>$tel,
            'name'=>$tel,
            'pid'=>$pid,
            'module_id'=>1,
            'status'=>1,
            's_time'=>time(),
        ];
        if(!is_null($deviceId)){
            $data['deviceId1']=$deviceId;
        }
        $add=model('member')->add($data);
        // 关联默认角色
        $defaultRole=model('role')->readAll(['is_default'=>1],0,['field'=>'id']);
        if(!empty($add)&&!empty($defaultRole)){
            $r=[];
            foreach ($defaultRole as $v) {
                $r[]=[
                    'role_id'=>$v['id'],
                    'member_id'=>$add['id'],
                ];
            }
            if(count($r)){
                model('role_member')->add($r);
            }
        }
        if(empty($add)){
            return $this->_register($tel,$pid);
        }
        return success('',0,$add);
    }
}
